package com.liit.console.controller.front;

import java.io.File;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liit.module.entity.Files;
import com.liit.module.frame.utils.ConfigUtil;
import com.liit.module.frame.utils.Const;
import com.liit.module.service.FilesService;

/**
 * @author dingweibo
 * @Title: FileController.java
 * @Description: 文件管理
 * @date 2016年1月3日
 */
@Controller
@RequestMapping(value = "/file")
public class FileController {

	private Logger logger = Logger.getLogger(getClass());

	@Resource
	FilesService filesService;

	@RequestMapping(value = "/clear")
	@ResponseBody
	public void clear() {
		try {
			logger.info("clear file invoke");
			long time = System.currentTimeMillis();
			Files where = new Files();
			where.setStatus(Const.FILES_STATUS_DELETE);
			List<Files> files = filesService.list(where);
			int count = 0;
			int i = 0;
			for (Files record : files) {
				if (record.getType() == 1) {
					i = filesService.deleteById(record.getId());
					if (i > 0) {
						count++;
					}
				} else {
					File file = new File(ConfigUtil.get("file.upload.path") + record.getPath());
					if (file.exists() && file.isFile()) {
						boolean isDelete = file.delete();
						if (isDelete) {
							i = filesService.deleteById(record.getId());
							if (i > 0) {
								count++;
							} else {
								logger.error(record.getId() + " Not updated,but file has been deleted");
							}
						}
					} else {
						logger.error(record.getId() + " File does not exist");
					}
				}
			}
			logger.info("本次操作待删除文件:" + files.size() + ",已删除文件：" + count + ",执行毫秒:" + (System.currentTimeMillis() - time));
		} catch (Exception e) {
			logger.error("执行异常", e);
		}
	}
}
